#!/usr/bin/php
<?PHP

// -------------------------- //
// --    CONFIGURATION     -- //
// -------------------------- //

$cfg['editor'] = 'vim -O {files} > `tty`';

$cfg['file_page']
=<<<PAGE
I'm the default page file.
Find me in <pre>{file}</pre>.
PAGE;

$cfg['file_template']
=<<<TEMPLATE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<link rel="shortcut icon" href="/p/favicon.ico" type="image/x-icon" />
		<link rel="stylesheet" type="text/css" href="<?PHP echo
			TeeWee::\$TEMPLATE->public_url('main.css');
		?>" />
		<title>TeeWee</title>
	</head>
	<body>
		<?PHP echo TeeWee::\$PAGE; ?>
	</body>
</html>
<html>
	<head></head>
	<body>
		I'm the default template from TeeWee.
		You can edit me in <pre>{file}</pre>.
		<div class="page">
			TeeWee
		</div>
	</body>
</html>
TEMPLATE;

$cfg['file_service']
=<<<SERVICE
I'm the default service file.
Find me in <pre>{file}</pre>.
SERVICE;

// -------------------------- //
// -- END OF CONFIGURATION -- //
// -------------------------- //

/** Go to the base of the TeeWee installation **/
function go_down() {
	if(file_exists('.teewee'))
		return;
	chdir('..');
	go_down();
}

/** Setup the tool's variables **/
function setup() {
	global $cl, $cfg, $argv;
	go_down();
	$cl['name']			= basename($argv[0]);
	$cl['ini']			= ".{$cl['name']}.ini";
	if(file_exists($cl['ini']))
		$cfg = array_merge(parse_ini_file($cl['ini'],$cfg));
	$cl['width']		= 80;
	$cl['header']		= "{$cl['name']} -- TeeWee's resource control tool";
	$cl['usage']		= "{$cl['name']} type command (name)+";
	$cl['footer']		= "{$cl['name']} -h | help | --help shows this help page";
	
	$cl['help_type']
=<<<TYPE
  type      page | template | service
    The type of resource you wish to control.
TYPE;

	$cl['help_command']
=<<<COMMAND
  command   create | delete | edit
    What do you wish to do with the given resource.
      - Create  create the resource directory structure
      - Delete  remove the resource directory structure
      - Edit    {$cfg['editor']} on the resource(s)
COMMAND;

	$cl['help_name']
=<<<NAME
  name+     path(s) for the resource(s).
    For pages this means it will be visible on http://my.tee.wee/\$name
NAME;

}

/** Print the help page **/
function print_help($problem,$specific) {
	global $cl;
	echo $cl['header']."\n";
	echo "Usage: {$cl['usage']}\n";
	echo "       {$cl['footer']}\n\n";
	if($specific)
		echo wordwrap($cl['help_'.$specific],$cl['width'])."\n\n";
	else foreach($cl as $k => $v) if(preg_match('/^help_/',$k))
		echo wordwrap($v,$cl['width'])."\n\n";
	if($problem) {
		echo str_pad('',$cl['width'],'-')."\n";
		echo "ERROR :: $problem\n";
		echo str_pad('',$cl['width'],'-')."\n";
	}
	exit;
}

/** Type processing **/
function resource($type) {
	global $cl, $argv;
	if(sizeof($argv) < 4)
		print_help('No '.$type.' name(s) supplied.','name');
	$names = array_slice($argv,3);
	switch($argv[2]) {
	case 'create':	create_resource($type,$names);break;
	case 'delete': 	delete_resource($type,$names);break;
	case 'edit':		edit_resource($type,$names);break;
	default:
		print_help("Unknown command '{$argv[2]}' for resource.",'command');
	}
}

function get_private($type,$name) {
	return 'resources/'.$type.'s/'.$name;
}

function get_public($type,$name) {
	return 'www/p/resources/'.$type.'s/'.$name;
}

function replace_all($subject,$replaces) {
	foreach($replaces as $pattern => $replace)
		$subject = preg_replace('/{'.$pattern.'}/',$replace,$subject);
	return $subject;
}

// CREATE
function create_resource($type,$names) {
	foreach($names as $name) {
		checked_create(get_private($type,$name),
			array($type => '.php'));
		checked_create(get_public($type,$name),
			array());
	}
}

function checked_create($dir,$files) {
	global $cfg;
	if(is_file($dir))
		print_help("Can't create: '$dir' is a file",'name');
	else if(is_dir($dir))
		echo "Directory '$dir' already exists. Not creating.\n";
	else {
		mkdir($dir,0755,true);
		foreach($files as $f => $ext) {
			$file = $dir.'/'.$f.$ext;
			$template = replace_all($cfg["file_$f"],array(
				'file' => $file,
			));
			file_put_contents($file,$template);
		}
	}
}

// DELETE
function confirm_delete($file) {
	if(!file_exists($file)) {
		echo "You want to delete '$file' but it doesn't exist.\n";
		return false;
	}
	echo "Are you sure you wish to delete '$file'? (y/N): ";
	$val = trim(strtolower(`read answer; echo \$answer`));
	
	if($val == 'yes' || $val == 'y') {
		if(is_dir($file))
			rmdir($file);
		else
			unlink($file);
		echo "removed '$file'\n";
		return true;
	}
	
	echo "Not removing '$file'\n";
	return false;
}

function delete_rec($file) {
	$delete = true;
	if(is_dir($file)) {
		foreach(scandir($file) as $sub)
			if($sub != '.' && $sub != '..')
				$delete = delete_rec($file.'/'.$sub);
		if($delete)
			confirm_delete($file);
		else
			echo "Not deleting directory '$file' since it is not empty.\n";
	}
	else
		$delete = confirm_delete($file);
	return $delete;
}

function delete_resource($type,$names) {
	foreach($names as $name) {
		delete_rec(get_private($type,$name));
		delete_rec(get_public($type,$name));
	}
}

// EDIT
function edit_resource($type,$names) {
	global $cfg;
	if(sizeof($names) != 1)
		print_help('Only one '.$type.' can be editted at a time.',null);
	$name = $names[0];
	$public =  get_public($type,$name);
	$private = get_private($type,$name);
	$cmd = replace_all($cfg['editor'],array(
		'files'	=>
			escapeshellarg($private).' '.
	 		escapeshellarg($public)
	));
	passthru($cmd);
}

/** Process the command **/
function go() {
	global $argc, $argv;
	setup();
	if($argc < 2) {
		print_help(null,null);
	}
	switch($argv[1]) {
		case '-h':
		case '-help':
		case '--help':
		case 'help': print_help(null,null); break;
		case 'template':
		case 'page':
		case 'service':
			resource($argv[1]);break;
		default:
			print_help('Unknown resource type: '.$argv[1],'type');
	}
}

go();

?>
